<template>
  <div>
    <!-- 面包屑导航区 -->
    <Breadcrumb :List = "list"></Breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type = "primary" @click = "showaddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        class = "treetable"
        :data = "cateList"
        :columns = "column"
        :selection-type = "false"
        :expand-type = "false"
        show-index index-text = "#"
        border :show-row-hover = "false">
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" style="color:lightgreen" v-if = "scope.row.cat_delete === false"></i>
          <i class="el-icon-error" style="color:red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if = "scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if = "scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type = "primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type = "danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10,20,50,100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="30%"
      @close = "addCateDialogClosed">
      <!-- 添加分类表单 -->
      <el-form :model="addCateFrom" status-icon :rules="addCateFromRules" ref="addCateFromRef" label-width="100px">
        <el-form-item label="分类名称" prop = "cat_name">
          <el-input v-model="addCateFrom.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectKeys"
            :options="parentCateList"
            expand-trigger="hover"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
            change-on-select>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="修改分类信息"
      :visible.sync="editDialogVisible"
      width="30%"
      @close = "editCateDialogClosed">
      <el-form :model="editCateFrom" :rules="editCateFromRules" ref="editCateFromRef" label-width="100px">
        <el-form-item label="分类编号">
          <el-input v-model="editCateFrom.cat_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop = "cat_name">
          <el-input v-model="editCateFrom.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '../Breadcrumb.vue'
export default {
  components: { Breadcrumb },
  data () {
    var rules = {
      required: true,
      message: '请输入分类名称',
      trigger: 'blur'
    }
    return {
      list: ['商品管理', '商品分类'],
      editDialogVisible: false,
      cateList: [],
      // 总数据条数
      total: 0,
      // 控制添加分类对话框的显示与隐藏
      addDialogVisible: false,
      // 选中的父级分类的id数组
      selectKeys: [],
      CateInfo: {},
      // 父级分类列表
      parentCateList: [],
      // 编辑表单
      editCateFrom: {
        cat_id: '',
        cat_name: ''
      },
      editCateFromRules: {
        cat_name: [
          rules
        ]
      },
      // 将要添加的分类的验证规则
      addCateFromRules: {
        cat_name: [
          rules
        ]
      },
      // 添加分类的表单数据对象
      addCateFrom: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 为table指定类的定义
      column: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用的模板名称
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 删除商品分类
    async deleteCate (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除商品分类失败')
      }
      this.$message.success('删除商品分类成功')
      this.getCateList()
    },
    // 根据id查询商品分类
    async showeditDialog (id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$http.error('查询商品分类失败')
      }
      this.editCateFrom = res.data
      this.editDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.parentCateList = res.data
    },
    // 修改分类信息
    async editCate () {
      const { data: res } = await this.$http.put('categories/' + this.editCateFrom.cat_id, {
        cat_name: this.editCateFrom.cat_name
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改分类信息失败!')
      }
      this.$message.success('修改分类信息成功')
      this.editDialogVisible = false
      this.getCateList()
    },
    // 显示编辑对话框
    showaddDialog () {
      this.getParentCateList()
      this.addDialogVisible = true
    },
    // 修改每页显示条数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 修改页码
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 选择项发生变化
    parentCateChange () {
      // 如果selectKeys数组中的length大于0,证明选中了父级分类
      // 反之则没有选中任何父级分类
      if (this.selectKeys.length > 0) {
        // 父级分类的id
        this.addCateFrom.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        // 为当前分类的等级赋值
        this.addCateFrom.cat_level = this.selectKeys.length
      } else {
        this.addCateFrom.cat_pid = 0
        this.addCateFrom.cat_level = 0
      }
    },
    // 点击按钮添加新的分类
    addCate () {
      this.$refs.addCateFromRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('categories', this.addCateFrom)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败!')
        }
        this.$message.success('添加分类成功!')
        this.addDialogVisible = false
        this.getCateList()
      })
    },
    // 关闭时重置表单数据
    addCateDialogClosed () {
      this.$refs.addCateFromRef.resetFields()
      this.addCateFrom.cat_pid = 0
      this.addCateFrom.cat_level = 0
      this.selectKeys = []
    },
    // 关闭对话框事件
    editCateDialogClosed () {
      this.$refs.editCateFromRef.resetFields()
    }
  },
  created () {
    this.getCateList()
  }
}
</script>

<style scoped>
.treetable{
  margin-top: 15px;
}
.el-cascader{
  width: 100%;
}
</style>
